/**
 * $Id: HTMLTextShape.java,v 1.5 2010-10-28 10:41:05 gaudenz Exp $
 * Copyright (c) 2010, Gaudenz Alder, David Benson
 */
package com.kg.rails.component.editor.shape;

import com.kg.rails.component.editor.canvas.Graphics2DCanvas;
import com.kg.rails.component.editor.util.Constants;
import com.kg.rails.component.editor.util.EditorLightweightLabel;
import com.kg.rails.component.editor.util.EditorUtils;
import com.kg.rails.component.editor.view.CellState;

import javax.swing.*;
import java.awt.*;
import java.util.Map;

public class HTMLTextShape implements ITextShape {

    /**
     * Specifies if linefeeds should be replaced with breaks in HTML markup.
     * Default is true.
     */
    protected boolean replaceHtmlLinefeeds = true;

    /**
     * Returns replaceHtmlLinefeeds
     */
    public boolean isReplaceHtmlLinefeeds() {
        return replaceHtmlLinefeeds;
    }

    /**
     * Returns replaceHtmlLinefeeds
     */
    public void setReplaceHtmlLinefeeds(boolean value) {
        replaceHtmlLinefeeds = value;
    }

    /**
     *
     */
    public void paintShape(Graphics2DCanvas canvas, String text,
                           CellState state, Map<String, Object> style) {
        EditorLightweightLabel textRenderer = EditorLightweightLabel
                .getSharedInstance();
        CellRendererPane rendererPane = canvas.getRendererPane();
        Rectangle rect = state.getLabelBounds().getRectangle();
        Graphics2D g = canvas.getGraphics();

        if (textRenderer != null
                && rendererPane != null
                && (g.getClipBounds() == null || g.getClipBounds().intersects(
                rect))) {
            double scale = canvas.getScale();
            int x = rect.x;
            int y = rect.y;
            int w = rect.width;
            int h = rect.height;

            if (!EditorUtils.isTrue(style, Constants.STYLE_HORIZONTAL, true)) {
                g.rotate(-Math.PI / 2, x + w / 2, y + h / 2);
                g.translate(w / 2 - h / 2, h / 2 - w / 2);

                int tmp = w;
                w = h;
                h = tmp;
            }

            // Replaces the linefeeds with BR tags
            if (isReplaceHtmlLinefeeds()) {
                text = text.replaceAll("\n", "<br>");
            }

            // Renders the scaled text
            textRenderer.setText(EditorUtils.createHtmlDocument(style, text));
            textRenderer.setFont(EditorUtils.getFont(style, canvas.getScale()));
            g.scale(scale, scale);
            rendererPane.paintComponent(g, textRenderer, rendererPane,
                    (int) (x / scale) + Constants.LABEL_INSET,
                    (int) (y / scale) + Constants.LABEL_INSET,
                    (int) (w / scale), (int) (h / scale), true);
        }
    }

}
